package com.gss.security.persistence;

import org.apache.log4j.Logger;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

import com.gss.security.domain.UserDetailsDTO;



public class CustomDAOAuthenticationProvider extends DaoAuthenticationProvider {
	
	Logger logger = Logger.getLogger(CustomDAOAuthenticationProvider.class);
	
	@Override
	protected void additionalAuthenticationChecks(UserDetails userDetails,
			UsernamePasswordAuthenticationToken authenticationToken)
			throws AuthenticationException {
		logger.debug("User who is going to be connected: " + userDetails.getUsername());
		super.additionalAuthenticationChecks(userDetails, authenticationToken);
		((UserDetailsDTO)userDetails).setTxtPassword(authenticationToken.getCredentials().toString());
		logger.debug("customauthprovider: " + userDetails.getUsername());
	}
	
	@Override
	public Authentication authenticate(Authentication authenticationSupplied)
			throws AuthenticationException {

		String txtPassword = null;
        if(null != authenticationSupplied.getCredentials()){
            txtPassword =  authenticationSupplied.getCredentials().toString();
        }
        Authentication authentication =   super.authenticate(authenticationSupplied);
       
        if(null != authentication.getPrincipal() && authentication.getPrincipal() instanceof UserDetailsDTO && null != txtPassword){
            ((UserDetailsDTO)authentication.getPrincipal()).setTxtPassword(txtPassword);
        }
        return authentication;
	}
}